Skip to content

Conversation

zombieJ
Copy link
Member

@zombieJ zombieJ commented Jul 1, 2025

fix ant-design/ant-design#54173
close #756

Summary by CodeRabbit

  • 文档

    • 简化了示例 React 组件,聚焦于动态字段监听的最小化表单演示。
  • 重构

    • 优化了表单字段监听逻辑,提升了依赖追踪与状态更新的简洁性和可靠性。
  • 测试

    • 更新了动态监听字段的测试用例,验证动态切换字段时 UI 能正确显示对应的值。

Copy link

vercel bot commented Jul 1, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
field-form ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 1, 2025 8:19am

Copy link

coderabbitai bot commented Jul 1, 2025

"""

Walkthrough

本次变更主要重构了 useWatch 的内部实现,优化了依赖追踪和回调触发逻辑,支持 selector 方式动态监听表单字段。文档与测试用例同步简化,聚焦于动态切换监听字段值的场景,移除了冗余组件和不必要的警告,提升了代码可读性和稳定性。

Changes

文件/分组 变更摘要
docs/examples/debug.tsx 精简示例,移除大数据和自定义 WatchCom,聚焦动态 selector 监听演示
src/useWatch.ts 重构 useWatch,优化依赖追踪与回调触发,移除警告和冗余逻辑
tests/useWatch.test.tsx 重写动态监听测试用例,验证 selector 方式动态切换字段值

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Form
    participant useWatch

    User->>Form: 填写表单
    Form->>useWatch: 注册 selector 监听
    useWatch->>Form: 订阅值变更
    Form-->>useWatch: 通知值变更
    useWatch->>User: 触发回调,返回 selector 选中的值
    User->>Form: 切换 selector 字段
    Form-->>useWatch: 重新触发监听
    useWatch->>User: 返回新字段值
Loading

Assessment against linked issues

Objective Addressed Explanation
useWatch selector 方式在嵌套 Form.List 下取值正确 (#54173)
修复 useWatch 不更新的问题,优化监听回调参数和依赖处理 (#756)
优化 useWatch 变量命名和依赖,提升可读性和稳定性 (#756)

Assessment against linked issues: Out-of-scope changes

(未发现超出关联 issue 目标的功能性代码变更。)

Suggested reviewers

  • crazyair

Poem

兔子跳跃表单间,
useWatch 监听更灵便。
selector 切换随心愿,
值变即现不再悬。
代码精简又清新,
测试通过笑盈盈!
🐰✨
"""

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/useWatch.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the config "prettier" to extend from. Please check that the name of the config is correct.

The config "prettier" was referenced from the config file in "/.eslintrc.js".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 27328cb and 1c2a469.

📒 Files selected for processing (1)
  • src/useWatch.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/useWatch.ts
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment
  • Commit Unit Tests in branch useWatch-dynamic

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

triggerUpdate();

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isValidForm, flattenDeps]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

方法的话,那每次 render 就是新的方法吧?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

我想的是,如果 dependencies 是方法,那判断返回的值,stringify处理,如果改变了就 render

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

我想的是,如果 dependencies 是方法,那判断返回的值,stringify处理,如果改变了就 render

就是这么做的。

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

现在是只要 render 了,flattenDeps 就变了

image

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

哦,只是 triggerUpdate 执行了,但是 setValue 还是判断变没变

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
docs/examples/debug.tsx (1)

9-10: 建议移除注释的代码行

注释的代码行展示了旧的 API 用法,但在示例中保留它可能会造成混淆。建议完全移除以保持代码简洁。

-  // const val = Form.useWatch(keyName ? 'name' : 'age', form);
   const val = Form.useWatch(values => values[keyName ? 'name' : 'age'], form);
tests/useWatch.test.tsx (1)

429-460: 测试逻辑正确且验证了动态监听功能

测试成功验证了动态字段监听的功能,从检查警告改为验证实际行为是正确的方向。测试逻辑清晰地验证了从监听 'light' 字段切换到 'bamboo' 字段时值的正确更新。

小建议:可以考虑添加更多边界情况的测试,比如切换到不存在的字段名。

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 35e81ea and 27328cb.

📒 Files selected for processing (3)
  • docs/examples/debug.tsx (1 hunks)
  • src/useWatch.ts (2 hunks)
  • tests/useWatch.test.tsx (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/useWatch.ts (2)
src/FieldContext.ts (1)
  • HOOK_MARK (5-5)
src/utils/valueUtil.ts (3)
  • getValue (6-6)
  • getNamePath (15-17)
  • setValue (6-6)
docs/examples/debug.tsx (1)
tests/common/InfoField.tsx (1)
  • Input (9-11)
🪛 GitHub Actions: ✅ test
src/useWatch.ts

[error] 7-7: ESLint: 'InternalNamePath' is defined but never used. (@typescript-eslint/no-unused-vars)


[error] 10-10: ESLint: 'WatchCallBack' is defined but never used. (@typescript-eslint/no-unused-vars)

🔇 Additional comments (6)
docs/examples/debug.tsx (2)

14-27: 很好的动态监听示例实现

这个简化的示例很好地展示了新的动态监听功能。使用选择器函数而不是静态字段名是一个很好的演示,清楚地展示了 API 的新功能。


3-3: 路径已验证:相对导入路径正确

已确认 docs/examples/components/Input.tsx 文件存在,import Input from './components/Input' 路径无误。示例代码简化清晰,完美展示了新 API 的动态监听功能,批准合并。

src/useWatch.ts (4)

120-133: triggerUpdate 函数实现正确

使用 useEvent 包装 triggerUpdate 函数是一个很好的设计选择,确保了函数引用的稳定性。函数正确处理了选择器函数和路径字符串两种情况,并且通过序列化比较避免了不必要的更新。


136-149: 依赖变化的 useEffect 实现良好

flattenDeps 的序列化处理很聪明,能够正确跟踪函数和路径的变化。立即触发更新确保了依赖变化时的及时响应。


152-165: 值变化监听的 useEffect 设计合理

将监听器注册分离到单独的 useEffect 中是好的关注点分离。正确地返回了取消注册函数进行清理。


90-167: 验证选择器函数的性能影响

新的选择器函数功能很强大,但需要确认在频繁更新时的性能表现,特别是当选择器函数比较复杂时。

建议在实际应用中测试复杂选择器函数的性能,或者考虑添加缓存机制来优化频繁调用的场景。

Copy link

codecov bot commented Jul 1, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 99.53%. Comparing base (35e81ea) to head (1c2a469).
Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #758      +/-   ##
==========================================
+ Coverage   99.45%   99.53%   +0.07%     
==========================================
  Files          19       19              
  Lines        1296     1287       -9     
  Branches      319      319              
==========================================
- Hits         1289     1281       -8     
+ Misses          7        6       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@zombieJ zombieJ merged commit 84bff2e into master Jul 2, 2025
13 checks passed
@zombieJ zombieJ deleted the useWatch-dynamic branch July 2, 2025 03:02
@coderabbitai coderabbitai bot mentioned this pull request Sep 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

useWatch selector 方式,在嵌套 Form.List 下取值错误
2 participants